package fmi.chesstern.game;

import java.util.LinkedList;

import fmi.chesstern.game.events.GameStateChangedEvent;
import fmi.chesstern.game.events.GameStateChangedListener;
import fmi.events.EventDispatcher;

public class GameState {
	private LinkedList<GameBoardState> moves;
	private MutableGameBoardState gameBoardState;
	private EventDispatcher<GameStateChangedEvent, GameStateChangedListener> dispatcher;
	
	public void addGameStateChangedListener(GameStateChangedListener listener) {
		dispatcher.addEventListener(listener);
	}
	
	public void removeGameStateChangedListener(GameStateChangedListener listener) {
		dispatcher.removeEventListener(listener);
	}
	
	public GameState() {
		moves = new LinkedList<GameBoardState>();
		gameBoardState = new MutableGameBoardState();
		dispatcher = new EventDispatcher<GameStateChangedEvent, GameStateChangedListener>();
		
		gameBoardState.addGameStateChangedListener(new GameStateChangedListener() {
			//@Override
			public void handleEvent(GameStateChangedEvent event) {
				dispatcher.dispatchEvent(event);
			}
		});
	}
	
	public boolean canUndoMove() {
		return !moves.isEmpty();
	}
	
	public void undoMove() {
		gameBoardState.setState(moves.poll());
	}
	
	public void makeMove(Move move) {
		moves.addFirst(gameBoardState.clone());
		gameBoardState.makeMove(move);
	}
	
	public void startNewGame() {
		moves.clear();
		gameBoardState.setState(new MutableGameBoardState());
	}
	
	public GameBoardState getGameBoardState() {
		return gameBoardState;
	}
}
